<template>
  <view class="content">
    <loading @end="showHome = true" @playAudio="handlePlayAudio1" />
    <home v-show="showHome" @start="handleStart" />
    <scene v-show="showScene" ref="scene" />
    <view
      :class="['music_box', !audio1Status && 'stop']"
      @click="handlePlayAudio1"
      v-if="showHome"
    />
    <view
      :class="['music_box', !audio2Status && 'stop']"
      @click="handlePlayAudio2"
      v-if="showScene"
    />
  </view>
</template>

<script>
import Loading from '@/components/loading'
import Home from '@/components/home'
import Scene from '@/components/scene'

export default {
  components: {
    Loading,
    Home,
    Scene,
  },
  data() {
    return {
      showHome: false,
      showScene: false,
      audio1: {},
      audio2: {},
      audio1Status: false,
      audio2Status: false,
    }
  },
  onLoad() {
    // var audio = document.createElement('audio')
    // audio.src = '/static/images/music1.mp3'
    // audio.loop = true
    // audio.addEventListener(
    //   'canplaythrough',
    //   function () {
    //     console.log('musice1 loaded!')
    //   },
    //   false
    // )
    // audio.load()

    this.playAudio1()
    this.playAudio2()
  },
  methods: {
    handleStart(index) {
      this.showScene = true
      this.showHome = false

      this.$nextTick(() => {
        this.$refs.scene.init()
        this.$refs.scene.start()
      })
      this.audio1.pause()
      this.handlePlayAudio2()
    },
    playAudio2() {
      this.audio2 = uni.createInnerAudioContext()
      console.log(this.audio2)
      this.audio2.loop = true
      this.audio2.src = `/static/images/music2.mp3`
      this.audio2.onPlay(() => {
        this.audio2Status = true
      })

      this.audio2.onError((res) => {
        console.log(res)
      })
    },
    playAudio1() {
      this.audio1 = uni.createInnerAudioContext()
      this.audio1.loop = true
      this.audio1.src = `/static/images/music1.mp3`
      this.audio1.onPlay(() => {
        this.audio1Status = true
      })

      this.audio1.onError((res) => {
        console.log(res)
      })
    },
    handlePlayAudio1() {
      if (this.audio1Status) {
        this.audio1.pause()
      } else {
        this.audio1.play()
      }
      this.audio1Status = !this.audio1Status
    },
    handlePlayAudio2() {
      if (this.audio2Status) {
        this.audio2.pause()
      } else {
        this.audio2.play()
      }
      this.audio2Status = !this.audio2Status
    },
    onUnload() {
      this.audio1.pause()
      this.audio2.pause()
    },
  },
}
</script>

<style lang="scss" scoped>
.music_box {
  width: 100rpx;
  height: 100rpx;
  z-index: 999;
  &:before {
    background-position: 0 -100rpx;
  }
  &.stop {
    background-position: 0 -200rpx;
  }
}
</style>
